package com.ruoyi.yuwen.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.newAdd.aliyun.sms.AliyunSmsService;
import com.ruoyi.common.newAdd.huaweiyunSms.SendSms;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.newAdd.utils.TimeUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yuwen.domain.Code;
import com.ruoyi.yuwen.service.ICodeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 验证码Controller
 * 
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/yuwen/code")
public class CodeController extends BaseController
{
    @Autowired
    private ICodeService codeService;

    /**
     * 查询验证码列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:list')")
    @GetMapping("/list")
    public TableDataInfo list(Code code)
    {
        startPage();
        List<Code> list = codeService.selectCodeList(code);
        return getDataTable(list);
    }

    /**
     * 导出验证码列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:export')")
    @Log(title = "验证码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Code code)
    {
        List<Code> list = codeService.selectCodeList(code);
        ExcelUtil<Code> util = new ExcelUtil<Code>(Code.class);
        util.exportExcel(response, list, "验证码数据");
    }

    /**
     * 获取验证码详细信息
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(codeService.selectCodeById(id));
    }

    /**
     * 新增验证码
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:add')")
    @Log(title = "验证码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Code code)
    {
        return toAjax(codeService.insertCode(code));
    }

    /**
     * 修改验证码
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:edit')")
    @Log(title = "验证码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Code code)
    {
        return toAjax(codeService.updateCode(code));
    }

    /**
     * 删除验证码
     */
    @PreAuthorize("@ss.hasPermi('yuwen:code:remove')")
    @Log(title = "验证码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(codeService.deleteCodeByIds(ids));
    }


    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */


    @Autowired
    private AliyunSmsService aliyunSmsService;

    //发送验证码（生成并存储验证码后发送验证码，有效期十分钟）
    /**
     * 新增验证码
     */
    @GetMapping("/front/codeAdd")
    public Res codeAdd(@RequestParam("phone")String phone) throws Exception {
        String codeStr = createCode(phone);
        //华为云短信
//        String sender = "1069368924410004849";
//        String templateId = "efef774461344bcea427d39c8072e289";
//        SendSms.sendSms(codeStr,phone,sender,templateId);

        //阿里云短信
        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", codeStr);
        String templateCode = "SMS_276485923";
        aliyunSmsService.sendMessage(phone,templateCode,codeMap);
        return Res.ok();
    }

    /**
     * 创建新的code码
     * @return
     */
    public String createCode(String phone){

        String rd = String.format("%06d",new Random().nextInt(999999));

        Code code = new Code();
        code.setPhone(phone);
        List<Code> list = codeService.selectCodeList(code);
        if (list.size()>0){
            code = list.get(0);
            code.setCode(rd);
            code.setAddTime(TimeUtil.getTime());
            codeService.updateCode(code);
        }else {
            code.setCode(rd);
            code.setAddTime(TimeUtil.getTime());
            codeService.insertCode(code);
        }
        return rd;
    }
}


